package com.yltrcc.blog.business.impl;

import com.alibaba.fastjson.JSONObject;
import com.yltrcc.blog.business.WeChatEntBaseService;
import com.yltrcc.blog.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * <a href="https://developer.work.weixin.qq.com/document/path/91770">企业微信机器人配置说明文档</a>
 */
@Service
public class WeChatEntBaseServiceImpl implements WeChatEntBaseService {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public void sendTextMsg(String url, String content, List<String> mobileList) {

        restTemplate.postForObject(url, buildTextParams(content, mobileList), JSONObject.class);
    }

    @Override
    public void sendMdMsg(String url, String content, List<String> mobileList) {
        JSONObject jsonObject = restTemplate.postForObject(url, buildMdParams(content, mobileList), JSONObject.class);
        System.out.println(jsonObject);
    }

    private HttpEntity<String> buildMdParams(String content, List<String> mobileList) {
        Map<String, Object> contents = new LinkedHashMap<>();
        //markdown内容，最长不超过4096个字节，必须是utf8编码
        contents.put("content", StringUtils.cutStr(content, 4090));
        contents.put("mentioned_mobile_list", mobileList);
        JSONObject requestParams = new JSONObject();
        requestParams.put("msgtype", "markdown");

        requestParams.put("markdown", contents);

        HttpHeaders requestHeaders = new HttpHeaders();
        // 重点是配置请求头内容类型为："application/json;charset=UTF-8""
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);

        // 封装参数
        return new HttpEntity<String>(requestParams.toString(), requestHeaders);
    }

    private HttpEntity<String> buildTextParams(String content, List<String> mobileList) {
        Map<String, Object> contents = new LinkedHashMap<>();
        contents.put("content", content);
        contents.put("mentioned_mobile_list", mobileList);
        JSONObject requestParams = new JSONObject();
        requestParams.put("msgtype", "text");
        requestParams.put("text", contents);

        HttpHeaders requestHeaders = new HttpHeaders();
        // 重点是配置请求头内容类型为："application/json;charset=UTF-8""
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);

        // 封装参数
        return new HttpEntity<String>(requestParams.toString(), requestHeaders);
    }
}
